import {
  BaseResponse,
  FamilyInfo,
  FamilyListReqParam,
  getFamilyList,
  userCreate,
  userUpdate
} from '@/services/family/api';
import {ModalForm, ProForm, ProFormSelect, ProFormText} from '@ant-design/pro-components';
import {message} from 'antd';
import to from 'await-to-js';
import {type FC, useLayoutEffect, useState} from 'react';
import {ROLE_TYPES} from "@/common/constants";

type ReportGenerateModalProps = {
  modalVisible: boolean;
  onOpenChange: (open: boolean) => void;
  onSubmit: (userInfo: UserCreateOrUpdateInfo) => void;
  userInfo: UserCreateOrUpdateInfo;
};

export type UserCreateOrUpdateInfo = {
  id?: number;
  role?: string;
  name?: string;
  activeFamilyId?: number;
  password?: string;
};

const UserNewOrUpdateModal: FC<ReportGenerateModalProps> = (props) => {
  const {userInfo, modalVisible, onOpenChange, onSubmit} = props;
  const [familyList, setFamilyList] = useState<FamilyInfo[]>([]);

  const handleQueryFamilyList = async (params: FamilyListReqParam): Promise<any> => {
    const [err, res] = await to(getFamilyList(params));
    if(err) {
      return message.error({
        content: err?.message || '家庭列表获取失败',
      });
    }
    setFamilyList(res?.result);
  };
  useLayoutEffect( () => {
    handleQueryFamilyList({})
  }, [1]);

  const handleUserCreate = async (
    userInfo: UserCreateOrUpdateInfo,
    callbackFun: (userId: number | undefined) => void,
  ) => {
    if (!userInfo || !userInfo.name || !userInfo.role || !userInfo.activeFamilyId || !userInfo.password) {
      return message.error({
        content: '用户名/所属家庭/角色/默认密码不能为空',
      });
    }
    const [err, res] = await to(userCreate(userInfo));
    if (err || !res) {
      return message.error({
        content: err?.message || '用户创建失败',
      });
    }
    return message.success({
      content: `${userInfo.name}(${userInfo.role})创建成功`,
      onClose: () => {
        callbackFun(res.result);
      },
    });
  };

  const handleUserUpdate = async (
    userInfo: UserCreateOrUpdateInfo,
    callbackFun: () => void,
  ) => {
    if (!userInfo || !userInfo.role || !userInfo.activeFamilyId) {
      return message.error({
        content: '用户角色/所属家庭不能为空',
      });
    }
    const [err, res] = await to(userUpdate(userInfo));
    if (err || !res) {
      return message.error({
        content: err?.message || '用户信息更新失败',
      });
    }
    return message.success({
      content: `${userInfo.name}(${userInfo.role})更新成功`,
      onClose: callbackFun,
    });
  };

  return (
    <ModalForm
      title={userInfo.id ? `${userInfo.name} - 用户编辑` : '创建用户'}
      open={modalVisible}
      onOpenChange={onOpenChange}
      width={600}
      onFinish={async (values) => {
        console.log('values', values);

        if (!userInfo.id) {
          const _userInfo: UserCreateOrUpdateInfo = {
            role: values.role,
            name: values.name,
            activeFamilyId: values.activeFamilyId,
            password: values.password,
          };
          handleUserCreate(_userInfo, (userId) => {
            _userInfo.id = userId;
            onSubmit(_userInfo);
          });
          return true;
        }

        const _userInfo: UserCreateOrUpdateInfo = {id: userInfo.id, name: values.name, role: values.role, activeFamilyId: values.activeFamilyId};
        handleUserUpdate(_userInfo, () => {
          userInfo.name = values.name;
          userInfo.role = values.role;
          userInfo.activeFamilyId = values.activeFamilyId;
          onSubmit(userInfo);
        });
        return true;
      }}
      submitTimeout={2000}
      modalProps={{
        okText: '保 存',
        destroyOnClose: true,
      }}
      initialValues={userInfo}
    >
      <ProForm.Group style={{width: '100%'}}>
        <ProFormText name="name" label="用户名称" placeholder="请输入用户名称" />
        <ProFormSelect
          fieldProps={{
            style:  {
              width: 200
            },
            showSearch: true,
          }}
          options={familyList?.map((item) => ({
            label: item.code + ": " + item.name,
            value: item.id,
          }))}
          colSize={100}
          name="activeFamilyId"
          label="所属家庭"
          placeholder="请选择所属家庭"
        />
        <ProFormSelect
          fieldProps={{
            style:  {
              width: 200
            },
            showSearch: true,
          }}
          options={ROLE_TYPES.map((item) => ({value: item, label: item}))}
          name="role"
          label="所属角色"
          placeholder="请选择所属角色"
        />
        <ProFormText name="password" label="默认密码" placeholder="无需修改则留空" />
        {userInfo.id && <div style={{color: 'red', fontWeight: 'bold'}}>用户名和所属家庭的修改是高危操作，请务必谨慎！</div>}
      </ProForm.Group>
    </ModalForm>
  );
};

export default UserNewOrUpdateModal;
